//
//  ViewController.m
//  NSURLSessionDemo
//
//  Created by sheepyellow on 2017/3/17.
//  Copyright © 2017年 sheepyellow. All rights reserved.
//

#import "ViewController.h"

@interface ViewController ()
@property (strong, nonatomic) IBOutlet UIActivityIndicatorView *spinner;
@property (strong, nonatomic) IBOutlet UIWebView *webView;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (IBAction)loadData:(id)sender {
    //开始加载数据，让spinner转起来
    [self.spinner startAnimating];
    
    // 创建Data Task, 用于打开公司主页
    NSURL* url = [NSURL URLWithString:@"https://git.oschina.net/"];
    NSURLRequest* request = [NSURLRequest requestWithURL:url];
    NSURLSession* session = [NSURLSession sharedSession];
    NSURLSessionDataTask* dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        //输出返回的状态码，请求成功的话为200
        [self showResponseCode:response];
        NSAssert(data, @"data不能为空");
        [self.webView loadData:data MIMEType:@"text/html" textEncodingName:@"utf-8" baseURL:nil];
        
        //加载数据完毕，停止spinner
        [self.spinner stopAnimating];
        
    }];
    [dataTask resume];
}

-(void)showResponseCode:(NSURLResponse*)response {
    NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*)response;
    NSInteger responseStatusCode = httpResponse.statusCode;
    NSLog(@"%ld",responseStatusCode);
}

- (IBAction)uploadFile:(id)sender {
//    NSURL* URL = [NSURL URLWithString:@"http://example.com/upload"];
//    NSURLRequest* request = [NSURLRequest requestWithURL:URL];
//    NSData* data = ...; //获取上传文件数据
//    
//    NSURLSession* session = [NSURLSession sharedSession];
//    NSURLSessionUploadTask* uploadTask = [session uploadTaskWithRequest:request fromData:data completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
//        // ..
//    }];
//    [uploadTask suspend];
}

- (IBAction)downloadFile:(id)sender {
    [self.spinner startAnimating];
    
    NSURL* URL = [NSURL URLWithString:@"http://b.hiphotos.baidu.com/image/w%3D2048/sign=6be5fc5f718da9774e2f812b8469f919/8b13632762d0f703b0faaab00afa513d2697c515.jpg"];
    NSURLRequest* request = [NSURLRequest requestWithURL:URL];
    NSURLSession* session = [NSURLSession sharedSession];
    NSURLSessionDownloadTask* downloadTask = [session downloadTaskWithRequest:request completionHandler:^(NSURL * _Nullable location, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        NSString* documentPath = [self getDocumentsPath];
        NSURL* documentsDirectoryURL = [NSURL fileURLWithPath:documentPath];
        NSURL* fileURL = [documentsDirectoryURL URLByAppendingPathComponent:[[response URL] lastPathComponent]];
        // 如果该路径下文件已经存在，就要像将其移除，在移除文件
        NSFileManager* fileManager = [NSFileManager defaultManager];
        if ([fileManager fileExistsAtPath:[fileURL path] isDirectory:NULL]) {
            [fileManager removeItemAtURL:fileURL error:NULL];
        }
        [fileManager moveItemAtURL:location toURL:fileURL error:NULL];
        
        //webView中加载图片文件
        NSURLRequest* showImage_request = [NSURLRequest requestWithURL:fileURL];
        [self.webView loadRequest:showImage_request];
        [self.spinner stopAnimating];
    }];
    
    [downloadTask resume];
}

-(NSString *)getDocumentsPath {
    NSArray* documents = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString* documentPath = documents[0];
    return documentPath;
}

@end
